
Component({
  data: {
    modelinput: '',
    productList: [],
    inputModel: false,
    categoryList:[],
    activeIndex:-1,
  },

  methods: {
    onShow() {
      // this.getList()
      // this.getCategory()
    },
    // 手动输入
    bindViewTap() {
      this.setData({
        inputModel: true
      })
    },
    //扫码
    scanCode() {
      const _this = this
      wx.scanCode({
        scanType: ['barCode'],
        success: (res) => {
          _this.getInfo(res.result)
        }
      })
    },
    handlestoreCodeOK() {
      if (this.data.modelinput) {
        this.getInfo(this.data.modelinput)
      }
    },
    extractBracketContent(str:string) {
      const regex = /\[(.*?)\]/g;
      const matches = [];
      let match;
      
      while ((match = regex.exec(str)) !== null) {
          matches.push(match[1]);
      }
      
      return matches;
  },
    sendUrl(data: any) {
      const _this=this
      // 考虑查询isbn后是否会有多本图书出现的情况
      // 若有增加选择
      // 否则直接插入数据
      // 9787201188614无法录入（西南联大） 儒林外史无作者 小妇人不对
      // 是否存在 人间少年
      wx.request({
        url: `https://api.douban.com/v2/book/isbn/:${data}`,
        method: 'GET',
        data: { apiKey: '0ac44ae016490db2204ce0a042db2916' },
        header: { 'Content-Type': 'json' },
        success: (res) => {
          console.log(res.data)
          const {data}=res
          const tags=data.tags.map(i=>{return i.name})
          const author=data.author[0]
          let simpleCountry='中'
          // let country='中国'
          const ifForeign=author&&(author.indexOf('[')>-1&&author.indexOf(']')>-1)
          if(ifForeign){
            // 获得【】内的国家简称
            simpleCountry= _this.extractBracketContent(author)[0]
          }
          const param = { title: data.title, author: data.author, cover: data.images.small,isbn:data.isbn13,series:data.series?.title,publisher:data.publisher,country:simpleCountry,binding:data.binding,tags:tags.join(','),author_intro:data.author_intro, translator:data.translator,subtitle:data.subtitle,pages:data.pages,pubdate:data.pubdate,price:data.price}
          this.add(param)
          // 将出版社、作者、系列、国家插入表中
          // const inTags=tags.map(item=>{return item.name})
          this.addCategory({type:'1',name:data.publisher,cover: data.images.small})
          this.addCategory({type:'2',name:data.author.join(','),cover: data.images.small})
          this.addCategory({type:'4',name:simpleCountry,cover: data.images.small})
          if(data.series){
            this.addCategory({type:'3',name:data.series.title,cover: data.images.small})
          }
          this.setData({modelinput:''})
        },
        fail: (err) => console.error(err)
      });
    },
    // 详情
    startDetailsOnClick(e:any) { 
      const data=e.currentTarget.dataset.item.isbn
      wx.navigateTo({
        url: '../detail/detail?id='+ encodeURIComponent(data),
      })
    },
    handlestoreCodeNo() {
      this.setData({
        inputModel: false
      })
    },
    // 插入接口
    add(data: any) {
      const _this = this
      wx.request({
        url: `http://localhost:8888/api/book/add`,
        method: 'POST',
        data: data,
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: (res) => {
          console.log(res.data)
          if(res.data.code=='200'){
            // _this.getList()
            const child = _this.selectComponent('#myBook');
            child.getList();
            _this.setData({inputModel:false })
          }
        },
        fail: (err) => console.error(err)
      });
    },
    // 插入分类接口
    addCategory(data:any){
      const _this = this
      wx.request({
        url: `http://localhost:8888/api/classify/add`,
        method: 'POST',
        data: data,
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: (res) => {
          console.log(res.data)
          
        },
        fail: (err) => console.error(err)
      });
    },
    // 接口---查询数据库是否存在该数据
    getInfo(data: any) {
      const _this = this
      wx.request({
        url: `http://localhost:8888/api/book/getId`,
        method: 'GET',
        data: {isbn:data},
        header: { 'Content-Type': 'json' },
        success: (res) => {
          console.log(res.data,'录过的书')
          if(res.data.code=='200'){
              if(res.data.data.length){
                // 存在则提示
                wx.showToast({
                  title: '该书已录入过',
                  icon: 'error',
                  duration: 1000
                })
                _this.setData({inputModel:false,modelinput:'' })
              }else{
                _this.sendUrl(data)
              }
          }
        },
        fail: (err) => console.error(err)
      });
    },
    // 搜索页
    search(){
      // wx.navigateTo({
      //   url: '../search/search'
      // })
    },

  },
})
